package md.draw;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import md.constants.FieldType;
import md.map.GameMap;
import md.settings.Settings;

public class MapPainter {

	private static Image image;
	
	public static boolean needRefresh = true;
	
	public final static void drawMap(Graphics g, int width, int height) {
		//System.out.println("width = " + width + ", height = " + height);
		
		if(image == null)
			image = Image.createImage(width, height);
		
		if(needRefresh) {
			drawMapToImage(image);
			needRefresh = false;
		}
		
		g.drawImage(image, 0, 0, 0);
	}
	
	private final static void drawMapToImage(Image image) {
		int width = Settings.mapWidth * Settings.cellSize;
		int height = Settings.mapHeight * Settings.cellSize;
		
		Graphics ig = image.getGraphics();
		
		ig.setColor(200, 200, 0);
		ig.fillRect(0, 0, width, height);

		ig.setColor(255, 255, 200);
		ig.fillRect(3, 3, width-6, height-6);
		
		ig.setColor(128, 128, 0);
		ig.drawRect(2, 2, width-4, height-4);

		for(int i=0;i<GameMap.map.length;i++)
			drawCell(ig, GameMap.decodeX(i), GameMap.decodeY(i), GameMap.map[i]);

		drawPath(ig, GameMap.defaultPath);
		
		drawEndPoint(ig, GameMap.decodeX(GameMap.startPoint), GameMap.decodeY(GameMap.startPoint));
		drawEndPoint(ig, GameMap.decodeX(GameMap.endPoint), GameMap.decodeY(GameMap.endPoint));
		
		
	}
	
	private final static void drawCell(Graphics g, int x, int y, int type) {
		
		if(type != FieldType.EMPTY) {
			g.setColor(0, 0, (Math.abs(type) * 80) % 255);
			g.fillRect(x * Settings.cellSize, y * Settings.cellSize, Settings.cellSize, Settings.cellSize);
		}

		g.setColor(200, 200, 200);
		g.drawRect(x * Settings.cellSize, y * Settings.cellSize, Settings.cellSize, Settings.cellSize);

	}
	
	private final static void drawEndPoint(Graphics g, int x, int y) {
		g.setColor(64, 64, 64);
		g.fillRect(x * Settings.cellSize + 1, y * Settings.cellSize + 1, Settings.cellSize - 2, Settings.cellSize - 2);
	}

	private final static void drawPath(Graphics g, short[] path) {
		if(path == null) {
			System.err.println("empty path");
			return;
		}
		for(int i=0;i<path.length;i++) {
			int x = GameMap.decodeX(path[i]);
			int y = GameMap.decodeY(path[i]);
			g.setColor(255, 255, i % 255);
			g.fillRect(x * Settings.cellSize + 3, y * Settings.cellSize + 3, Settings.cellSize - 6, Settings.cellSize - 6);

		}
	}

}
